<template>
  <div v-if="authStore.isAuthenticated" class="match-record-container">
    <h2>Match Records</h2>
    <a-alert v-if="error" type="error">{{ error }}</a-alert>
    <a-spin :spinning="loading">
      <a-table :columns="columns" :data-source="matchRecords" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-button type="link" @click="viewDetails(record)">Details</a-button>
            <a-button v-if="!authStore.isGuest && !authStore.isUser" type="link" @click="editMatch(record.matchId)">Edit</a-button>
            <a-popconfirm  title="Are you sure delete this match?" ok-text="Yes" cancel-text="No"
              @confirm="deleteMatch(record.matchId)" @cancel="cancel">
              <a href="#" style="color: red;">Delete</a>
            </a-popconfirm>
          </template>
          <template v-else-if="column.key === 'matchDate'">
            {{ formatDate(record.matchDate) }}
          </template>
        </template>
      </a-table>
    </a-spin>
  </div>
  <a-alert v-else class="no-data" type="warning" show-icon>
    <template #message>
      You must log in/register to view match records.
    </template>
    <template #description>
      Redirecting to the login page in {{ countdown }} seconds...
    </template>
  </a-alert>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';
import axios from '../axios';
import dayjs from 'dayjs';
// 新增：定义 Match 接口（根据模拟数据推断字段）
interface Match {
  matchId: number | null; // 将 id 改为 matchId 并允许 null
  opponentName: string | null;
  position: string | null;
  matchDate: string | null;
  knockoutTime: string | null;
  result: string | null;
  firstHalfScore: string | null;
  secondHalfScore: string | null;
}
const countdown = ref(5); // 倒计时初始值
const authStore = useAuthStore();
const router = useRouter();
const matchRecords = ref<Match[]>([]);
const loading = ref(false);
const error = ref('');

// 表格列定义
const columns = [
  {title: 'Match Id',dataIndex: 'matchId', key: 'matchId'},
  { title: 'Opponent Name', dataIndex: 'opponentName', key: 'opponentName' },
  { title: 'Position', dataIndex: 'position', key: 'position' },
  { title: 'Match Date', dataIndex: 'matchDate', key: 'matchDate' },
  { title: 'Knockout Time', dataIndex: 'knockoutTime', key: 'knockoutTime' },
  { title: 'Result', dataIndex: 'result', key: 'result' },
  { title: 'First Half Score', dataIndex: 'firstHalfScore', key: 'firstHalfScore' },
  { title: 'Second Half Score', dataIndex: 'secondHalfScore', key: 'secondHalfScore' },
  { title: 'Actions', key: 'actions' },
];

const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm');
};

// 获取比赛列表
const fetchMatches = async () => {
  try {
    loading.value = true;
    const res = await axios.get('/matchs');
    matchRecords.value = res.data.data; // 根据ApiResponse结构调整
  } catch (err) {
    error.value = 'Failed to fetch match records';
  } finally {
    loading.value = false;
  }
};

const cancel = (e: MouseEvent) => {
  console.log(e);
};
// 实现删除方法
const deleteMatch = async (matchId: number) => {
  try {
    await axios.delete(`/matchs/${matchId}`);
    fetchMatches(); // 重新获取数据以更新表格
  } catch (err) {
    error.value = 'Failed to delete match record';
  }
};

// 实现修改方法
const editMatch = (matchId: number) => {
  router.push({
    name: 'EditMatchRecord',
    params: { matchId } // 直接使用 matchId
  });
};
// 查看详情方法
const viewDetails = (record: any) => {
  router.push({
    name: 'MatchRecordDetail',
    params: { matchId: record.matchId } // 使用正确的字段名
  });
};

// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
  if (!isAuthenticated) {
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        router.push({ name: 'Auth' });
      }
    }, 1000);
  }
}, { immediate: true }); // 立即执行
// 页面加载时获取数据
onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchMatches();
  }
});
</script>

<style scoped>
.match-record-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}
</style>